class Snake{
    element: HTMLElement
    head: HTMLElement
    bodies: HTMLCollection
    constructor(){
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake>div') as HTMLElement
        this.bodies = this.element.getElementsByTagName('div')
    }
    get X(){
        return this.head.offsetLeft
    }
    get Y(){
        return this.head.offsetTop
    }
    set X(value:number){
        if (this.X === value) return
        if (value < 0 || value > 290) throw '蛇撞墙了，GAME OVER'
        // 左右掉头
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value){
            if (this.X > value){
                value = this.X + 10
            } else {
                value = this.X - 10
            }
        }
        this.moveBody()
        this.head.style.left = value + 'px'
        this.checkHeadBody()
    }
    set Y(value:number){
        if (this.Y === value) return
        if (value < 0 || value > 290) throw '蛇撞墙了，GAME OVER'
        // 上下掉头
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value){
            if (this.Y > value){
                value = this.Y + 10
            } else {
                value = this.Y - 10
            }
        }
        this.moveBody()
        this.head.style.top = value + 'px'
        this.checkHeadBody()
    }
    addBody(){
        this.element.insertAdjacentHTML('beforeend', '<div class="black"></div>')
    }
    moveBody(){
        for(let i=this.bodies.length-1;i>0;i--){
            const x = (this.bodies[i-1] as HTMLElement).offsetLeft
            const y = (this.bodies[i-1] as HTMLElement).offsetTop
            ;(this.bodies[i] as HTMLElement).style.cssText = `left:${x}px;top:${y}px`
        }
    }
    checkHeadBody(){
        for(let i=this.bodies.length-1;i>0;i--){
            const x = (this.bodies[i] as HTMLElement).offsetLeft
            const y = (this.bodies[i] as HTMLElement).offsetTop
            if(this.X === x && this.Y === y){
                throw '撞着自己了，GAME OVER'
            }
        }
    }
}
export default Snake